package com.l024.android_ljl;
import android.app.Application;
import android.os.Build;
import android.text.TextUtils;

import androidx.multidex.MultiDex;

import com.getkeepsafe.relinker.ReLinker;
import com.l024.android_ljl.cache.CacheManager;
import com.l024.android_ljl.constant.ApiConstant;
import com.quantstack.llcommonlibrary.LLCommon;
import com.quantstack.llhttplibrary.EasyHttp;
import com.quantstack.llhttplibrary.EasyHttpConfig;
import com.tencent.mmkv.MMKV;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author wu_ming_zhi_bei
 * @date 2021/5/6 14:23
 * @Notes
 */
public class App extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        MultiDex.install(this);
        LLCommon.init(this);
        initHttp();
        initMMKV();
    }

    private void initMMKV(){
        if (Build.VERSION.SDK_INT == 19) {
            //一些 Android设备（API level 19）在安装/更新APK 时可能出错, 导致 libmmkv.so 找不到。
            String dir = getFilesDir().getAbsolutePath() + "/mmkv";
            MMKV.initialize(dir, new MMKV.LibLoader() {
                @Override
                public void loadLibrary(String libName) {
                    //开源库[ReLinker](https://github.com/KeepSafe/ReLinker) 专门解决这个问题
                    ReLinker.loadLibrary(App.this, libName);
                }
            });
        } else {
            //👇初始化代码，数据默认存储在：
            //context.getFilesDir().getAbsolutePath() + "/mmkv"
            MMKV.initialize(this);
        }
    }

    private void initHttp() {

        final Interceptor mTokenInterceptor = new Interceptor() {
            @NotNull
            @Override
            public Response intercept(@NotNull Interceptor.Chain chain) throws IOException {
                Request originalRequest = chain.request();
                String token = CacheManager.getInstance().getCacheToken();
                if (TextUtils.isEmpty(token)) {//表示第一次登陆还没拉取过token
                    return chain.proceed(originalRequest);//执行登陆的操作
                }
                //此处表示已有token 这时只需要判断401即可
                Request authorised = originalRequest.newBuilder()
                        .header("X-Token",token)//此处的token 是你保存在本地的
                        .build();
                return chain.proceed(authorised);//执行此次请求
            }
        };

        EasyHttp.init(new EasyHttpConfig() {
            @Override
            public String baseUrl() {
                return ApiConstant.BASE_URL;
            }

            @Override
            public boolean debug() {
                return true;
            }

            @Override
            public Map<String, String> addHeaders() {
                Map<String,String> headers = new HashMap<>();
                String token = CacheManager.getInstance().getCacheToken();
                if(!TextUtils.isEmpty(token)){
                    headers.put("X-Token",token);
                }
                return headers;
            }

            @Override
            public Map<String, String> addParams() {
                //Map<String,String> params = new HashMap<>();
                //params.put("lang","en");
                //return params;
                return null;
            }

            @Override
            public Set<Interceptor> addInterceptor() {
                HashSet<Interceptor> set = new HashSet<>();
                set.add(mTokenInterceptor);
                return set;
            }
        });
    }
}
